package com.hoshiicloud.user.service.impl.organization;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.common.utils.UidGenerate4C;
import com.hoshiicloud.user.entity.organization.ComOrganizationUsers;
import com.hoshiicloud.user.feign.IdGeneratorService;
import com.hoshiicloud.user.mapper.organization.ComOrganizationUsersMapper;
import com.hoshiicloud.user.param.organization.ComOrganizationUsersQueryParam;
import com.hoshiicloud.user.service.organization.ComOrganizationUsersService;
import com.hoshiicloud.user.service.rbac.IMemberService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 租户机构用户 服务实现类
 * </p>
 *
 * @author campchen
 * @since 2019-05-27
 */
@Slf4j
@Service
public class ComOrganizationUsersServiceImpl extends ServiceImpl<ComOrganizationUsersMapper, ComOrganizationUsers> implements ComOrganizationUsersService {

    @Autowired
    private IdGeneratorService idGeneratorService;

    @Autowired
    private IMemberService memberService;


    /**
     * @param id
     * @return com.hoshiicloud.organization.entity.ComOrganizationUsers
     * @description: 根据id查询租户机构用户
     */
    @Override
    @Cacheable(cacheNames = "ComOrganizationUsers", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Logable(authName = "机构（供应商）管理-租户机构用户 -查询租户机构用户 ")
    public ComOrganizationUsers getById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public ComOrganizationUsers getByMemeberId(Long memberId) {
        Wrapper<ComOrganizationUsers> wrapper = Wrappers.<ComOrganizationUsers>query().lambda().eq(ComOrganizationUsers::getMemberId, memberId);
        return baseMapper.selectOne(wrapper);
    }

    @Cacheable(cacheNames = "ComOrganizationUsers", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#usercode")
    @Logable(authName = "供应商信息-机构表 -查询机构表 ")
    @Override
    public ComOrganizationUsers getByOrgcode(String usercode) {
        Wrapper<ComOrganizationUsers> wrapper = Wrappers.<ComOrganizationUsers>query().lambda().eq(ComOrganizationUsers::getUserCode, usercode);
        return baseMapper.selectOne(wrapper);
    }

/*    @Override
    public List<ComOrganizationUsers> getByEntity(ComOrganizationUsers COU) {
        QueryWrapper<ComOrganizationUsers> queryWrapper = new QueryWrapper();
        queryWrapper.eq(COU.getMemberid() != null, "memberid", COU.getMemberid());
        queryWrapper.eq(StringUtils.isNotBlank(COU.getUsercode()), "usercode", COU.getUsercode());
        queryWrapper.eq(StringUtils.isNotBlank(COU.getQrcode()), "qrcode", COU.getQrcode());
        return baseMapper.selectList(queryWrapper);
    }*/


    /**
     * @param entity
     * @return boolean
     * @description: 新增租户机构用户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "ComOrganizationUsers", allEntries = true)
    @Logable(authName = "机构（供应商）管理-租户机构用户-新增租户机构用户")
    public String insert(ComOrganizationUsers entity) {
        //循环结束条件
        boolean flag = true;
        String code = null;
        //设置超次
        int num = 1;
        UidGenerate4C idWorker = new UidGenerate4C(num);
        String id = idGeneratorService.queryGeneratorId();
        if (id == null || id == "") {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        Response response = Response.data(memberService.getById(entity.getMemberId()));
        if (response.getData() == null || response.getCode() != 200) {
            throw new ServiceException(CommonError.error("新增失败,会员id错误"));
        }
        while (flag) {
            num++;
            //5代表供应商 1代表租户层面
            code = 5 + 1 + String.valueOf(idWorker.getNextId()).substring(10, 17);
            System.out.println("做测试用：com.hoshiicloud.organization.service.impl " + code);
            ComOrganizationUsers comOrganizationUsers = getByOrgcode(code);
            if (comOrganizationUsers == null) {
                flag = false;
            }
            if (num > 1000) {
                throw new ServiceException(CommonError.error("ComOrganizationUsers下usercode自动生成重复超过1000次，请通知管理员！"));
            }
        }
        entity.setUserCode(code);
        entity.setId(Long.parseLong(id));
        entity.setCreatedTime(LocalDateTime.now());
        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        return id;
    }

    /**
     * @param entity
     * @return boolean
     * @description: 修改租户机构用户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "ComOrganizationUsers", allEntries = true)
    @Logable(authName = "机构（供应商）管理-租户机构用户管理-修改租户机构用户")
    public boolean updateById(ComOrganizationUsers entity) {
        entity.setModifiedTime(LocalDateTime.now());
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改失败"));
        }
        return true;
    }

    /**
     * @param param 查询条件
     * @return IPage
     * @description: 分页查询租户机构用户
     */
    @Logable(authName = "机构（供应商）管理-租户机构用户管理-分页查询租户机构用户")
    @Cacheable(cacheNames = "ComOrganizationUsers", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    public IPage<ComOrganizationUsers> getPage(ComOrganizationUsersQueryParam param) {
        QueryWrapper<ComOrganizationUsers> queryWrapper = new QueryWrapper<ComOrganizationUsers>();
        queryWrapper.eq(param.getMemberId() != null && param.getMemberId() != 0, "member_id", param.getMemberId());
        queryWrapper.eq(StringUtils.isNotBlank(param.getUserCode()), "user_code", param.getUserCode());
        queryWrapper.eq(StringUtils.isNotBlank(param.getQrCode()), "qr_code", param.getQrCode());
        queryWrapper.eq(StringUtils.isNotBlank(param.getWorkTelphone()), "work_telphone", param.getWorkTelphone());
        queryWrapper.eq(StringUtils.isNotBlank(param.getPosition()), "position", param.getPosition());
        queryWrapper.eq(StringUtils.isNotBlank(param.getEducational()), "educational", param.getEducational());
        queryWrapper.eq(StringUtils.isNotBlank(param.getProfessional()), "professional", param.getProfessional());
        queryWrapper.eq(param.getHireDate() != null, "hire_date", param.getHireDate());
        queryWrapper.eq(StringUtils.isNotBlank(param.getEmail()), "email", param.getEmail());
        queryWrapper.eq(StringUtils.isNotBlank(param.getOfficelocation()), "officelocation", param.getOfficelocation());
        queryWrapper.eq(param.getLocked() != null, "locked", param.getLocked());
        queryWrapper.eq(StringUtils.isNotBlank(param.getWxOpenId()), "wx_open_id", param.getWxOpenId());
        queryWrapper.eq(StringUtils.isNotBlank(param.getWxUnionId()), "wx_union_id", param.getWxUnionId());
        queryWrapper.eq(StringUtils.isNotBlank(param.getWxName()), "wx_name", param.getWxName());
        queryWrapper.eq(StringUtils.isNotBlank(param.getWxPic()), "wx_pic", param.getWxPic());
        queryWrapper.eq(StringUtils.isNotBlank(param.getQqOpenId()), "qq_open_id", param.getQqOpenId());
        queryWrapper.eq(param.getDeleted() != null, "deleted", param.getDeleted());
        queryWrapper.eq(param.getLastLoginTime() != null, "last_login_time", param.getLastLoginTime());
        IPage<ComOrganizationUsers> page = new Page<>(Long.parseLong(param.getPageNumber()), Long.parseLong(param.getPageSize()));
        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "ComOrganizationUsers", allEntries = true)
    @Logable(authName = "机构（供应商）管理-租户机构用户管理-删除租户机构用户")
    public boolean deleteById(long id) {
        ComOrganizationUsers data = this.getById(id);
        if (data == null) {
            log.error("删除租户机构部门异常，无法找到租户机构部门记录");
            throw new ServiceException("删除租户机构部门异常，无法找到租户机构部门记录");
        }
        int row = baseMapper.deleteById(id);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("删除失败"));
        }
        return true;
    }

    @Override
    @Cacheable(cacheNames = "ComOrganizationUsers", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    @Logable(authName = "机构（供应商）管理-租户机构用户管理-根据id集合查询租户机构用户")
    public List<ComOrganizationUsers> getByIds(List<Long> ids, String key) {
        return baseMapper.selectBatchIds(ids);
    }

    /**
     * @Author:campchen
     * @Description:
     * @Date:上午 10:45 2019/6/14
     * @Param:
     * @return:
     */
    @Override
    @Cacheable(cacheNames = "ComOrganizationUsers", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    @Logable(authName = "后台用户操作-根据公司信息进行分页查询")
    public IPage<ComOrganizationUsers> getPage(IPage<ComOrganizationUsers> page, QueryWrapper<ComOrganizationUsers> queryWrapper, String key) {
        return baseMapper.selectPage(page, queryWrapper);
    }
}
